package com.redstar.HappyRefresh.manage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.redstar.HappyRefresh.authority.Authority;
import com.redstar.HappyRefresh.pojo.BasePage;
import com.redstar.HappyRefresh.pojo.Result;
import com.redstar.HappyRefresh.pojo.Type;
import com.redstar.HappyRefresh.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/type")
public class TypeManage { // 分类管理端

    @Autowired
    private TypeService typeService; // 分类服务

    @GetMapping("/{id}")
    @Authority("admin:type:get")
    public Result get(@PathVariable Long id){ // 根据id获取分类信息
        return Result.succeed().data(typeService.getById(id));
    }

    @GetMapping("/page")
    @Authority("admin:type:page")
    public Result page(BasePage basePage){ // 分页查询分类信息
        IPage<Type> page = typeService.page(basePage.page());
        return Result.succeed().data(page.getRecords()).count(page.getTotal());
    }

    @PostMapping
    @Authority("admin:type:add")
    public Result add(@RequestBody @Validated Type type){ // 添加分类
        int count = typeService.count(new LambdaQueryWrapper<Type>().eq(Type::getName, type.getName()));
        if (count == 1) {
            return Result.fail().message("分类已存在");
        }
        type.setIcon("fa " + type.getIcon());
        typeService.save(type);
        return Result.succeed().message("添加成功");
    }

    @PutMapping
    @Authority("admin:type:update")
    public Result update(@RequestBody @Validated Type type){ // 修改分类
        int count =  typeService.count(new LambdaQueryWrapper<Type>().eq(Type::getName, type.getName()));
        // 校验修改后的分类名称是否与其他分类名称冲突
        if (count == 1) {
            return Result.fail().message("修改后的分类与其他分类冲突");
        }
        typeService.updateById(type);
        return Result.succeed().message("修改成功");
    }

    @DeleteMapping("/{id}")
    @Authority("admin:type:delete")
    public Result delete(@PathVariable Long id){ // 删除分类
        typeService.removeById(id);
        return Result.succeed().message("删除成功");
    }
}
